<script setup lang="ts">
    import {
        Promotion,
        User,
        Crop,
        EditPen,
        SwitchButton,
        CaretBottom,
    } from '@element-plus/icons-vue'
    import axios from 'axios';
    import moment from 'moment';
    import {
        useRouter
    } from 'vue-router';
    import {
        ref,
        onMounted
    } from 'vue';
    import {
        ElMessage
    } from 'element-plus';
    import {
        StudentUpdateService,
        UpdatePasswordService,
        studentLoginService
    } from '@/api/student.js'
    import {
        ProfessionListAllSerivce
    } from '@/api/profession.js'
    import {
        TeacherListAllSerivce
    } from '@/api/teacher.js'
    import {
        MainClassListAllSerivce
    } from '@/api/mainClass.js'
    const router = useRouter();
    const jwtToken = localStorage.getItem('studentJwtToken');
    // 设置请求头部，包含jwt令牌
    const config = {
        headers: {
            Authorization: `Bearer ${jwtToken}`
        }
    };

    const studentModel = ref({
        studentId: '',
        studentName: '',
        studentPassword: '',
        studentEmail:'',
        studentPhoto: '',
        studentPhone:'',
        studentSex:'',
        studentTime:'',
        studentNation:'',
        studentNativePlace:'',
        classId:1,
        className:'',
        teacherId:1,
        teacherName:'',
        professionId:1,
        professionName:''
    });

    const professions = ref([{
        "professionId":1,
        "professionName":"",
        "professionType":""
    }])
    const professionAll = async () => {
        try {
            const result = await ProfessionListAllSerivce();
            professions.value = result.data;
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '搜索出错',
            });
        }
    }
    const teachers = ref([{
        "teacherId":1,
        "teacherName":"",
        "teacherPhone":"",
        "teacherPhoto":"",
        "professionId":""
    }])
    const teacherAll = async () => {
        try {
            const result = await TeacherListAllSerivce();
            teachers.value = result.data;
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '搜索出错',
            });
        }
    }
    const mainClasss = ref([{
        "classId":1,
        "className":"",
        "classNumber":"",
        "teacherId":"",
        "professionId":""
    }])
    const mainClassAll = async () => {
        try {
            const result = await MainClassListAllSerivce();
            mainClasss.value = result.data;
        } catch (error) {
            ElMessage({
                type: 'error',
                message: '搜索出错',
            });
        }
    }
    const fetchData = async () => {
        try {
            console.log(config)
            const response = await axios.get('http://localhost:9090/student/jwt', config);
            const studentData = response.data.data.student;
            if (studentData) {
                studentModel.value.studentId = studentData.studentId;
                studentModel.value.studentName = studentData.studentName;
                studentModel.value.studentPassword = studentData.studentPassword;
                studentModel.value.studentEmail = studentData.studentEmail;
                studentModel.value.studentPhone=studentData.studentPhone
                studentModel.value.studentSex = studentData.studentSex;
                studentModel.value.studentTime=studentData.studentTime;
                studentModel.value.studentNation=studentData.studentNation;
                studentModel.value.studentNativePlace=studentData.studentNativePlace;
                studentModel.value.studentPhoto = studentData.studentPhoto;
                studentModel.value.classId = studentData.classId;
                studentModel.value.teacherId = studentData.teacherId;
                studentModel.value.professionId=studentData.professionId;
                // 获取对应的专业名称并添加到教师对象中
                const result1 = await ProfessionListAllSerivce();
                professions.value = result1.data;
                const profession = professions.value.find(prof => prof.professionId === studentModel.value.professionId);
                if (profession) {
                    studentModel.value.professionName = profession.professionName;
                }
                const result2 = await TeacherListAllSerivce();
                teachers.value = result2.data;
                const teacher = teachers.value.find(teac=>teac.teacherId === studentModel.value.teacherId);
                if(teacher){
                    studentModel.value.teacherName = teacher.teacherName;
                }
                const result3 = await MainClassListAllSerivce();
                mainClasss.value = result3.data;
                const mainClass = mainClasss.value.find(mainc=>mainc.classId===studentModel.value.classId);
                if(mainClass){
                    studentModel.value.className = mainClass.className;
                }

                studentModel.value.studentTime = moment(studentModel.value.studentTime).format('YYYY-MM-DD');
            
                professionAll();
                teacherAll();
                mainClassAll();
            } else {
                console.error('User data not found in the response');
            }
        } catch (error) {
            console.log(error);
        }
    };

    onMounted(() => {
        fetchData();
    });
    const dialogVisible = ref(false)
    const avatarVisible = ref(false)

    const logout = () => {
        //清除用户的JWT令牌
        clearJWtToken();
        //重定向到登录页面
        router.push('/');
    };

    const clearJWtToken = () => {
        localStorage.removeItem('studentJwtToken');
    };
    const tempImg=ref();
    const uploadRef = ref()
    const updateImg = async () => {
        try {
            studentModel.value.studentPhoto=tempImg.value;
            let result = await StudentUpdateService(studentModel.value);
            if(result.code===1){
                ElMessage.success('修改成功');
                studentModel.value.studentPhoto=tempImg.value;
                tempImg.value='';
                uploadRef.value.clearFiles();
                avatarVisible.value = false;
            }else{
                ElMessage.error(result.msg);
            }
        } catch (error) {
            ElMessage.error('修改失败');
        }
    }

    const registerData = ref({
        studentPassword: '',
        repassword: ''
    });
    const passwordVisible = ref(false);
    const temp = ref();
    //校验密码的函数
    const checkRePassword = async () => {
        if (registerData.value.studentPassword === '') {
            ElMessage.error("请输入密码")
        } else if (registerData.value.studentPassword !== registerData.value.repassword) {
            ElMessage.error('两次输入的密码不一致')
        } else {
            temp.value = studentModel.value.studentPassword;
            studentModel.value.studentPassword = registerData.value.studentPassword;
            const result = await UpdatePasswordService(studentModel.value);
            if (result.code === 1) {
                ElMessage.success('修改密码成功');
                localStorage.removeItem('studentUserName');
                localStorage.removeItem('studentPassword');
                passwordVisible.value = false;
                clearPassData();
                temp.value = "";
            } else {
                ElMessage.error('修改密码失败');
                studentModel.value.studentPassword = temp.value;
            }
        }
    }

    const clearPassData = () => {
        registerData.value = {
            studentPassword: '',
            repassword: ''
        };
    }

    const handleSuccess=async(response)=>{
        tempImg.value=response.data;
    }

    const showDateForm=async()=>{
        avatarVisible.value=true;
        tempImg.value = studentModel.value.studentPhoto;
    }
</script>

<template>
    <el-container class="layout-container">
        <!-- 左侧菜单 -->
        <el-aside width="200px">
            <div class="el-aside__logo"></div>
            <!-- element-plus的菜单标签 -->
            <div style="width: 200px;height: 60px;margin: 0 auto;color: aliceblue;margin-left: 30px;margin-top: 40px;">
                <span style="font-size: 18px;"><b>
                学生管理系统</b></span>
            </div>
            <el-menu active-text-color="#ffd04b" background-color="#232323" text-color="#fff" router>
                <el-menu-item index="/stuforstudent">
                    <el-icon>
                        <Promotion />
                    </el-icon>
                    <span>成绩管理</span>
                </el-menu-item>
                <el-menu-item index="/stucourseforstudent">
                    <el-icon>
                        <Promotion />
                    </el-icon>
                    <span>课程管理</span>
                </el-menu-item>
            </el-menu>
        </el-aside>
        <!-- 右侧主区域 -->
        <el-container>
            <!-- 头部区域 -->
            <el-header>
                <div><strong>{{ studentModel.studentName }}</strong></div>
                <el-dropdown placement="bottom-end">
                    <span class="el-dropdown__box">
                        <el-avatar :src="studentModel.studentPhoto" />
                        <el-icon>
                            <CaretBottom />
                        </el-icon>
                    </span>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="profile" :icon="User" @click="dialogVisible=true">基本资料
                            </el-dropdown-item>
                            <el-dropdown-item command="avatar" :icon="Crop" @click="showDateForm()">修改信息
                            </el-dropdown-item>
                            <el-dropdown-item command="password" :icon="EditPen" @click="passwordVisible=true">重置密码
                            </el-dropdown-item>
                            <el-dropdown-item command="logout" :icon="SwitchButton" @click="logout">退出登录
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </el-header>
            <!-- 信息弹窗 -->
            <el-dialog v-model="dialogVisible" width="50%" :top="'calc(200px)'">
                <el-form :model="studentModel" label-width="100px" style="padding-right: 30px">
                    <el-row>
                        <el-col :span="8">
                    <el-form-item label="学生姓名:" prop="studentName">
                        {{ studentModel.studentName }}
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="学生密码:" prop="studentPassword">
                        {{ studentModel.studentPassword }}
                    </el-form-item>
                </el-col>
                    <el-col :span="8">
                    <el-form-item label="学生性别:" prop="studentSex">
                        {{ studentModel.studentSex }}
                    </el-form-item>
                </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                    <el-form-item label="学生邮箱:" prop="studentEmail">
                        {{ studentModel.studentEmail }}
                    </el-form-item>
                </el-col>
                    <el-col :span="12">
                    <el-form-item label="学生手机:" prop="studentPhone">
                        {{ studentModel.studentPhone }}
                    </el-form-item>
                </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                    <el-form-item label="学生民族:" prop="studentNation">
                        {{ studentModel.studentNation }}
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="学生籍贯:" prop="studentNativePlace">
                        {{ studentModel.studentNativePlace }}
                    </el-form-item>
                </el-col>
                </el-row>
                    <el-row>
                        <el-col :span="6">
                    <el-form-item label="所属专业:" prop="professionId">
                        {{ studentModel.professionName }}
                    </el-form-item>
                </el-col>
                    <el-col :span="6">
                    <el-form-item label="负责老师:" prop="teacherId">
                        {{ studentModel.teacherName }}
                    </el-form-item>
                </el-col>
                    <el-col :span="12">
                    <el-form-item label="所属班级:" prop="classId">
                        {{ studentModel.className }}
                    </el-form-item>
                </el-col>

                </el-row>
                <el-row>
                    <el-col :span="12">
                    <el-form-item label="学生照片:" prop="studentPhoto">
                        <div class="photo-cell">
                            <img v-if="studentModel.studentPhoto" :src="studentModel.studentPhoto" alt="Photo">
                            <img v-else src="@/assets/bap.png">
                        </div>
                    
                    </el-form-item>
                </el-col>
                    <el-col :span="12">
                    <el-form-item label="出生日期:" prop="studentTime">
                        {{ studentModel.studentTime }}
                    </el-form-item>
                </el-col>
                </el-row>
                </el-form>
                
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false" type="primary">确定</el-button>
                    </span>
                </template>
            </el-dialog>
            <!-- 修改弹窗 -->
            <el-dialog v-model="avatarVisible" width="40%">
                <el-form :model="studentModel" label-width="100px" style="padding-right: 30px">
                <el-row>
                    <el-col :span="12">
                    <el-form-item label="学生姓名" prop="studentName" style="width: 300px;">
                        <el-input v-model="studentModel.studentName" minlength="1"></el-input>
                    </el-form-item>
                    </el-col>
                    <el-col :span="12">
                    <el-form-item label="学生性别" prop="studentSex" style="width: 300px;">
                        <el-select v-model="studentModel.studentSex" placeholder="性别" style="width: 115px">
                                    <el-option label="男" value="男" />
                                    <el-option label="女" value="女" />
                                </el-select>
                    </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                    <el-form-item label="学生邮箱" prop="studentEmail" style="width: 300px;">
                        <el-input v-model="studentModel.studentEmail" minlength="1"></el-input>
                    </el-form-item>
                    </el-col>
                    <el-col :span="12">
                    <el-form-item label="学生手机" prop="studentPhone" style="width: 300px;">
                        <el-input v-model="studentModel.studentPhone" minlength="1"></el-input>
                    </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                    <el-form-item label="学生民族" prop="studentNation" style="width: 300px;">
                        <el-input v-model="studentModel.studentNation" minlength="1"></el-input>
                    </el-form-item>
                    </el-col>
                    <el-col :span="12">
                    <el-form-item label="学生籍贯" prop="studentNativePlace" style="width: 300px;">
                        <el-input v-model="studentModel.studentNativePlace" minlength="1"></el-input>
                    </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                    <el-form-item label="出生日期" prop="studentTime" style="width:300px">
                        <!-- <el-input v-model="StudentModel.studentTime" minlength="1"></el-input> -->
                        <el-date-picker
                        v-model="studentModel.studentTime"
                        type="date"
                        placeholder="Pick a day"
                        :size="size"
                        />
                    </el-form-item>
                    </el-col>
                    <el-col :span="12">
                    <el-form-item label="学生照片" prop="studentPhoto">
                        <el-upload
                            ref="uploadRef"
                            class="upload-demo"
                            action="http://localhost:9090/upload"
                            :limit="1"
                            :on-success="handleSuccess"
                        >
                            <el-button type="primary">select file</el-button>
                        </el-upload>
                    </el-form-item>
                    </el-col>
                </el-row>
                    <span style="margin-left: 350px;">
                        <el-button @click="avatarVisible = false ;updateImg()" type="primary">确定</el-button>
                    </span>
                </el-form>
            </el-dialog>

            <!-- 密码弹窗 -->
            <el-dialog v-model="passwordVisible" width="30%" :top="'calc(200px)'">
                <el-form :model="registerData" label-width="100px" style="padding-right: 30px">
                    <el-form-item prop="studentPassword" label="输入密码">
                        <el-input type="password" placeholder="请输入密码" v-model="registerData.studentPassword"></el-input>
                    </el-form-item>
                    <el-form-item prop="repassword" label="重复密码">
                        <el-input type="password" placeholder="请输入再次密码" v-model="registerData.repassword"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="checkRePassword" type="primary">确定</el-button>
                    </span>
                </template>
            </el-dialog>
            <!-- 中间区域 -->
            <el-main>
                <router-view></router-view>
            </el-main>
            <!-- 底部区域 -->
            <el-footer>学生管理系统 ©2024 Created by Sun</el-footer>
        </el-container>
    </el-container>
</template>

<style lang="scss" scoped>
    .layout-container {
        height: 100vh;

        .el-aside {
            background-color: #232323;


            .el-menu {
                border-right: none;
            }
        }

        .el-header {
            background-color: #fff;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .el-dropdown__box {
                display: flex;
                align-items: center;

                .el-icon {
                    color: #999;
                    margin-left: 10px;
                }

                &:active,
                &:focus {
                    outline: none;
                }
            }
        }

        .el-footer {
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            color: #666;
        }
    }

    .photo-cell {
        width: 80px;
        height: 80px;
    }

    .photo-cell img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .el-image {
        padding: 0 5px;
        max-width: 300px;
        max-height: 200px;
        width: 100%;
        height: 200px;
    }

    .image-slot {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        background: var(--el-fill-color-light);
        color: var(--el-text-color-secondary);
        font-size: 30px;
    }
</style>